import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-09-20
 * Time: 19:06
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void intelem(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap(){
        for (int parent = (this.usedSize-1-1)/2; parent >= 0 ; parent--) {
            shifDown(parent, this.usedSize);//没棵树结束时候都给个10，如果接着调整的节点比10大了。说明这棵树一定调整完了
        }
    }


    //alt+p+enter 直接生成

    /**
     *
     * @param parent 每棵子树调整的起始位置
     * @param usedSize 判断 每棵子树 什么时候  调整结束
     */
    private void shifDown(int parent, int usedSize) {
        int child = 2*parent+1;
        while(child < usedSize){
            //找到左右子树的最大值
            if(child+1 < usedSize && elem[child] < elem[child+1]){
                child++;
            }
            if(elem[child] > elem[parent]){
               swap(elem,child,parent);
                parent = child;
                child = 2*parent+1;
            }else{
                break;
            }
        }
    }

    //插入
    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        sitUp(usedSize);
        usedSize++;

    }


    private void swap(int[] elem, int i ,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }


    private void sitUp(int child) {
        int parent = (child-1)/2;
        while(parent >= 0){
            if (elem[parent] < elem[child]){
                swap(elem,child,parent);
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
    }

    public boolean isFull(){
        return elem.length == usedSize;
    }

    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int val = elem[0];
        swap(elem,0,usedSize-1);
        shifDown(0,usedSize-1);
        usedSize--;
        return val;
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }

    public void heapSort(){
        int end = usedSize-1;
        while(end > 0){
            swap(elem,0,end);
            shifDown(0,end);
            end--;
        }
    }

}
